<!--
 * @Author: hucc
 * @Date: 2021-10-18 20:26:15
 * @LastEditors: hucc
 * @LastEditTime: 2021-10-18 21:30:31
 * @Description: 
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖</title>
</head>

<body>
    <input type="text">
    <script>
        //获取节点
        input = document.querySelector('input');
        //oninput 输入时触发
        input.oninput = debounce(function() {
            console.log(this.value);
        }, 500);
        //fn delay形参  function(){} 500实参
        function debounce(fn, delay) {
            let timer;
            //把函数返回出去
            return function() {
                //内部timer访问外部的timer 闭包
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(() => {
                    //把fn指向改为箭头函数指向 input
                    //fn 是function(){console.log(this.value)}
                    fn.call(this);
                }, delay)
            }
        }
    </script>
</body>

</html>